<?php

namespace Users\Recover;

use Pinenut\Form;
use Pinenut\User\Auth\EmailPassword;
use Users\Helper\SmartRedirect;

class CheckCodeAction extends \Action
{
	protected static $isPublic = true;
	
	function privileges() {
		return '#unauthorized';
	}
	
	protected static $layout = "#layouts.column1Narrow";
	
	protected static $config = 'Users\Recover\CheckCodeFormConfig';

	static function pullParams() {
		return ['sessionId', 'isPost', 'isAjax'];
	}
	
	public function run()
	{
		
		// отрубаем кеширование если пост-запрос
		if ($this->request->_isPost) {
			$this->response->noCache(true);
		}
		
		$conf = static::$config;
		
		$formConfig = $conf::get();
		
		$form = new Form($this->request->_sessionId, 'checkCode', $formConfig);
		
		if ($this->request->_isPost && $this->request->_isAjax) {
			$form->process($this->request->params(), true);
			$this->response->content = $form->render();
			$this->response->noRender(true);
			return;
		} else if ($this->request->_isPost && !$this->request->onlyRender) {
			if (!$form->process($this->request->params())) {
				$this->response->form = $form;
				return;
			}
			$values = $form->getValues();
			$auth = EmailPassword::setRecoveryPassword($values['email'], 
					$values['recoveryCode'], $values['newPassword']);
			
			if ($auth) {
				$ref = $auth->profile->get ();
				if ($ref) {
					$profile = $ref->getEntity ();
				}
				if (! $profile) {
					throw new \Exception ( 'Profile not found' );
				}
				// аутентифицируем
				\Application::auth ()->login ( ( string ) $profile );
				$form->flush();
				
				$url = '/';
				
				$smartRedirectUrl = SmartRedirect::getRedirectPoint();
				if ($smartRedirectUrl !== null) {
					$url = $smartRedirectUrl;
					SmartRedirect::clearRedirectPoint();
				}
				
				$this->redirect($url);
			} 
		}
		else {
			$form->setValues(['email' => $this->request->email, 'recoveryCode' => $this->request->recoveryCode, 'newPassword' => '']);
		}
		
		$this->response->form = $form;
	}
}